package huichun_m

import (
	"frozen-go-mini/common/domain"
	"frozen-go-mini/common/resource/mysql"
)

// HuichunProduct  挥春产品
type HuichunProduct struct {
	mysql.Entity
	Spu       string `gorm:"column:spu"`        //  商品spu,如苹果6
	Sku       string `gorm:"column:sku"`        //  商品sku,如土豪金 16g 苹果6
	Name      string `gorm:"column:name"`       //  挥春名字
	Desc      string `gorm:"column:desc"`       //  描述
	Pics      string `gorm:"column:pics"`       //  图片,逗号隔开
	Price     int64  `gorm:"column:price"`      //  原价,单位分
	DiscPrice int64  `gorm:"column:disc_price"` //  折扣价,单位分
	Stock     int64  `gorm:"column:stock"`      //  库存
	Sales     int64  `gorm:"column:sales"`      //  销量
	Tags      string `gorm:"column:tags"`       //  标签,逗号隔开
	Sort      int64  `gorm:"column:sort"`       //  排序
	Status    int64  `gorm:"column:status"`     //  上下架 1:上架 0:下架
}

func (HuichunProduct) TableName() string {
	return "huichun_product"
}

// 获取商城页的数据
// 每个Spu获取销量最高的前8个
// return spu->products
func GetMarketList(model *domain.Model) map[string][]HuichunProduct {
	var spus []string
	if err := model.DB().Model(HuichunProduct{}).Select("DISTINCT(spu)").Scan(&spus).Error; err != nil {
		model.Log.Errorf("GetMarketList fail:%v", err)
	}
	res := make(map[string][]HuichunProduct)
	if len(spus) <= 0 {
		return res
	}
	for _, spu := range spus {
		var rows []HuichunProduct
		if err := model.DB().Model(HuichunProduct{}).Where("spu = ?", spu).Order("sales DESC,id DESC").Limit(8).Find(&rows).Error; err != nil {
			model.Log.Errorf("GetMarketList fail:%v", err)
			continue
		}
		res[spu] = rows
	}
	return res
}

func GetMarketDetail(model *domain.Model, id mysql.ID) HuichunProduct {
	var res HuichunProduct
	if err := model.DB().Model(HuichunProduct{}).Where("id = ?", id).First(&res).Error; err != nil {
		model.Log.Errorf("GetMarketDetail fail:%v", err)
	}
	return res
}

// 获取本店招牌
func GetHuichunHouseSpecialty(model *domain.Model) []HuichunProduct {
	var res []HuichunProduct
	if err := model.DB().Model(HuichunProduct{}).Where("is_top = 1 AND status = 1").Order("sort desc").Find(&res).Error; err != nil {
		model.Log.Errorf("GetHuichunHouseSpecialty fail:%v", err)
	}
	return res
}
